package com.ruix.app.widget;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.ruix.app.R;
import com.ruix.app.RuiApplication;
import com.ruix.app.manager.MediaPlayerManager;
import com.ruix.app.model.LessonInfo;
import com.ruix.app.service.MusicPlayerLisenter;
import com.ruix.app.service.MusicService;
import com.ruix.app.ui.adapter.LessonPicViewAdapter;
import com.ruix.app.util.DateUtil;
import com.ruix.app.util.LogUitl;
import com.ruix.app.util.ToastUtil;
import com.ruix.app.util.ViewUtil;

import java.io.File;
import java.io.IOException;

/**
 * Created by hadexs on 2017/5/21.
 */

public class LessonTopView extends RelativeLayout implements View.OnClickListener, SeekBar.OnSeekBarChangeListener,MusicPlayerLisenter {

    private LessonInfo lessonInfo;
    private ViewPager viewPager;
    private TextView picCount,leftTime;
    private SeekBar seekBar;
    private ImageView playView,fullScreen;
    private LessonPicViewAdapter pagerAdapter;
    private int pageSize;
    private int seekProgress; //滑动的进度
    private int lastProgress; //
    private String totalSecendsTime;
    private MusicService musicService;

    private LessonTopViewLestener viewLestener;

    public LessonTopView(Context context) {
        super(context);
        initView(context);
    }

    public LessonTopView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public LessonTopView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context){
        LinearLayout.inflate(context, R.layout.layout_lesson_top_view, this);
        int wight =  ViewUtil.getWindowWidth(context);
        RelativeLayout coantain =  (RelativeLayout) findViewById(R.id.rl_top_commtain);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) coantain.getLayoutParams();
        params.height = wight/2;
        params.width = wight;
        coantain.setLayoutParams(params); //设置16/8

        viewPager = (ViewPager)findViewById(R.id.picture_pager);
        picCount = (TextView) findViewById(R.id.tv_pic_count);
        leftTime = (TextView) findViewById(R.id.tv_left_time);
        seekBar = (SeekBar) findViewById(R.id.adiuo_seek_bar);
        playView = (ImageView) findViewById(R.id.btn_start_play);
        fullScreen =  (ImageView) findViewById(R.id.btn_full_screen);

        seekBar.setEnabled(false);
        seekBar.setMax(100);
        pagerAdapter = new LessonPicViewAdapter(context);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setCurrentItem(0);
        viewPager.setOffscreenPageLimit(3);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setCurrentPicCount(position,pageSize);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        seekBar.setOnSeekBarChangeListener(this);
        playView.setOnClickListener(this);
        fullScreen.setOnClickListener(this);
        musicService =RuiApplication.getInstance().getMusicService();
    }

    public void updateView(LessonInfo lessonInfo){
        this.lessonInfo = lessonInfo;
        if (lessonInfo != null){
            if (lessonInfo.getAlbum() != null && lessonInfo.getAlbum().size() > 0) {
                pageSize = lessonInfo.getAlbum().size();
                setCurrentPicCount(viewPager.getCurrentItem(), pageSize);
                pagerAdapter.setPicAddress(lessonInfo.getAlbum());
            }

            if (musicService != null && !TextUtils.isEmpty(lessonInfo.getAudio()) && !"null".equals(lessonInfo.getAudio())){
                if (!musicService.isPreparing()) {
                    musicService.prepareUrl(lessonInfo.getAudio());
                    musicService.addLisenter(this);
                }
            }

        }
    }

    private void setCurrentPicCount(int index,int total){
        index = index + 1;
        picCount.setText(index+"/"+total);
//        picCount.setText(12+"/"+123);
    }

    public void setCurrentPage(int index){
//        setCurrentPicCount
        if (index >=0) {
            viewPager.setCurrentItem(index);
        }
    }



    private void setAduioPayingState(){
        playView.setImageResource(R.drawable.lession_aduio_pause);
    }

    private void setAduioPausedState(){
        if (playView != null) {
            playView.setImageResource(R.drawable.audio_start_bg);
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (musicService != null) {
            int duration = musicService.getDuration();
            if (duration > 0) {
                this.seekProgress = progress * duration / seekBar.getMax();
            }
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        lastProgress = seekBar.getProgress();
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (musicService != null){
            if (musicService.isPlaying()) {
                int duration = musicService.getDuration();
                if (duration > 0) {
                    int progress = seekBar.getProgress();
                    this.seekProgress = progress * duration / seekBar.getMax();
                    musicService.seekTo(seekProgress);
                }
            } else if (musicService.isPreparing()){
                seekBar.setProgress(lastProgress);
            } else {
                int duration = musicService.getDuration();
                if (duration > 0) {
                    int progress = seekBar.getProgress();
                    this.seekProgress = progress * duration / seekBar.getMax();
                    musicService.seekTo(seekProgress);
                    musicService.start();
                    setAduioPayingState();
                }

            }
        }
    }


    @Override
    public void onSeekComplete(MediaPlayer mp) {
        totalSecendsTime =  DateUtil.millisecondToMinute(mp.getDuration());
        String currentPosition  =  DateUtil.millisecondToMinute(mp.getCurrentPosition());
        leftTime.setText(currentPosition+"/"+totalSecendsTime);
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {

    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        seekBar.setEnabled(true);
        float total =  mp.getDuration();
        int lastReport =  lessonInfo.getLastReport();
        if (total > 0) {
            if (lastReport > 0){
                float seekProgress = (lastReport / total) * 100;
                musicService.seekTo(lastReport);
                seekBar.setProgress((int) seekProgress);

//                onStopTrackingTouch(seekBar);

//                musicService.start();
//
//                musicService.seekTo((int) lastReport);
//                musicService.start();
            } else {
                totalSecendsTime =  DateUtil.millisecondToMinute(mp.getDuration());
                leftTime.setText("00:00"+"/"+totalSecendsTime);
            }
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        setAduioPausedState();
        if (seekBar != null) {
            seekBar.setProgress(0);
        }
        if (leftTime != null) {
            leftTime.setText("00:00" + "/" + totalSecendsTime);
        }
    }

    @Override
    public void onPlayerTick(int duration, int crrentPostion) {
        if (crrentPostion < duration) {
            totalSecendsTime = DateUtil.millisecondToMinute(duration);
            String currentPositionStr = DateUtil.millisecondToMinute(crrentPostion);
            leftTime.setText(currentPositionStr + "/" + totalSecendsTime);
            float progress = (float) crrentPostion / (float) duration * 100;
            seekBar.setProgress((int) progress);
        } else {
            if (musicService!= null) {
                musicService.seekTo(0);
            }
        }
    }

    @Override
    public void getCacheProgress(int progress) {

    }



    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_start_play:
//                mediaPlayer.start();
                if (musicService != null && lessonInfo !=null ){
                    if (TextUtils.isEmpty(lessonInfo.getAudio()) || "null".equals(lessonInfo.getAudio())){
                        ToastUtil.showNewErrorMsg("音频地址不合法");
                        return;
                    }
                    if (musicService.isPreparing()){
                        ToastUtil.showNewErrorMsg("加载中");
                    } else {
                        if (musicService.isPlaying()){
                            musicService.pause();
                            setAduioPausedState();
                        } else {
                            musicService.start();
                            setAduioPayingState();
                        }
//                        musicService.playPause();
                    }
                }

                break;

            case R.id.btn_full_screen:
                if (viewLestener != null){
                    viewLestener.fullScreen(viewPager.getCurrentItem());
                }

                break;
        }

    }

    public int currentPosition(){
        if (musicService != null) {
           return musicService.getCurrentPosition();
        }
        return 0;
    }

    public void release(){
        if (musicService != null) {
            musicService.pause();
            musicService.removeLisenter(this);
        }
    }


    public void setViewLestener(LessonTopViewLestener viewLestener) {
        this.viewLestener = viewLestener;
    }

    public interface  LessonTopViewLestener{
        void fullScreen(int currentItem);
    }



}
